package com.woniuxy.yogaapp.handler;

import com.woniuxy.yogaapp.pojo.Chat;
import com.woniuxy.yogaapp.service.WebSocketService;
import com.woniuxy.yogaapp.util.JsonUtil;
import com.woniuxy.yogaapp.util.SpringUtil;
import com.woniuxy.yogaapp.util.TimeUtil;
import com.woniuxy.yogaapp.util.WebSocketUtil;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * 处理WebSocket请求功能(私聊)
 */
@RestController
//表示接受的是STOMP协议提交的数据
@ServerEndpoint("/websocket/{meUid}")
public class WebSocketHandler {

    private  WebSocketService webSocketService ;



    //建立连接
    @OnOpen
    public void openSession(@PathParam("meUid")Integer meUid, Session session) {
        webSocketService = SpringUtil.getBean(WebSocketService.class);
        if (meUid == null || meUid == 0 || session == null) {
            return;
        }
        //把session放入map集合
        if (WebSocketUtil.MESSAGEMAP.get(meUid) == null) {
            WebSocketUtil.MESSAGEMAP.put(meUid, session);
        }
        System.out.println("加入成功");
    }
    @OnMessage
    public void onMessage(String message) {
        //发送的信息合法性判断
        if (message == null || message.length() == 0) {
            return;
        }
        //解析message数据
        Chat chat = JsonUtil.StringToObject(message);
        if (chat == null) {
            return;
        }
        //设置信息的时间
        chat.setMestime(TimeUtil.getNowDate());
        //发送数据
        int i = WebSocketUtil.sendChatToOne(chat);

        //根据发送是否成功设置消息的状态
        if (i == 1) {
            chat.setState("已读");
        } else {
            chat.setState("未读");
        }

        //把信息存入数据库中
        webSocketService.addChat(chat);
    }


    //离开聊天室
    @OnClose
    public void onClose(@PathParam("meUid")Integer uid,Session
            session) {
    //将当前用户从map中移除 注销
        WebSocketUtil.MESSAGEMAP.remove(uid);
    //关闭session
        try {
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(uid+"关闭session");
    }
    //连接异常
    @OnError
    public void onError(@PathParam("meUid")Integer uid,Session session,Throwable throwable) {

        throwable.printStackTrace();

        //将当前用户从map中移除 注销
        WebSocketUtil.MESSAGEMAP.remove(uid);
        //关闭session
        try {
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(uid+"出现异常");
    }


}
